﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using PersonaLibrary.Data;
using PersonaLibrary.Validation;

namespace PersonaLibrary.ViewModel.ConnectionViewModel
{
    internal class EditConnectionViewModel : LinqEditableItem<ConnectionJobEmplDep>
    {
        #region Private members

        private ValidationItem orgValid = new ValidationItem();
        private ValidationItem depValid = new ValidationItem();
        private ValidationItem empValid = new ValidationItem();
        private ValidationItem jobValid = new ValidationItem();

        #endregion

        #region Ctor

        public EditConnectionViewModel()
        {
            AllInit();
            EditableItem = new ConnectionJobEmplDep();
        }

        public EditConnectionViewModel(int id)
        {
            AllInit();
            EditableItem = Context.ConnectionJobEmplDeps.Single(x => ((ConnectionJobEmplDep)x).Id == id);
            orgValid.ValidationValue.Key = EditableItem.Department.Organization.Name;
            depValid.ValidationValue.Key = EditableItem.Department.Name;
            empValid.ValidationValue.Key = EditableItem.Employee.ToString();
            jobValid.ValidationValue.Key = EditableItem.Job.Name;
            orgValid.IsValid = true;
            depValid.IsValid = true;
            empValid.IsValid = true;
            jobValid.IsValid = true;
            SetEmplValidExpression();
        }

        #endregion

        #region Private method

        private void SetEmplValidExpression()
        {
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"\s+");
            string[] result = reg.Replace(empValid.ValidationValue.Key, " ").Split(" ".ToCharArray());
            switch (result.Length)
            {
            }
        }

        void EmpValidPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "ValidationValue")
            {
                SetEmplValidExpression();
            }
        }               

        void OrgValidPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "IsValid")
            {
                if (orgValid.IsValid)
                {
                }
            }
        }

        private void AllInit()
        {
            orgValid.PropertyChanged += OrgValidPropertyChanged;
            empValid.PropertyChanged += EmpValidPropertyChanged;
            InitOrgValid();
            InitJobValid();
            InitEmpValid();
            InitDepValid();
        }

        private void InitOrgValid()
        {         
        }

        private void InitDepValid()
        {
        }

        private void InitEmpValid()
        {
        }

        private void InitJobValid()
        {
        }

        #endregion

        #region Puplic properties

        public ValidationItem OrganizationValid
        {
            get { return orgValid; }
        }

        public ValidationItem DepartmentValid
        {
            get { return depValid; }
        }

        public ValidationItem EmployeeValid
        {
            get { return empValid; }
        }

        public ValidationItem JobValid
        {
            get { return jobValid; }
        }

        #endregion

        #region Parent override

        public override bool CanCommit()
        {
            if (!orgValid.IsValid) return false;
            if (!depValid.IsValid) return false;
            if (!empValid.IsValid) return false;
            if (!jobValid.IsValid) return false;
            return true;
        }

        public override void Commit()
        {
        	List<Organization> organizations =
        		Context.Organizations.Where(x => x.Name == orgValid.ValidationValue.Key).ToList();
			if (organizations.Count > 1)
			{
				MessageBox.Show(string.Format("Невозможно сохрать изменения так как есть органиации с одинаковым названием '{0}'",
				                              orgValid.ValidationValue));
				return;
			}

			if (organizations[0].Departments.Count(x => x.Name == depValid.ValidationValue.Key) > 1)
			{
				MessageBox.Show(string.Format("Невозможно сохрать изменения так как в организации '{0}' есть несколько отделов с одинаковым названием '{1}'",
											  orgValid.ValidationValue, depValid.ValidationValue));
				return;
			}

			EditableItem.Department = organizations[0].Departments.Single(x => x.Name == depValid.ValidationValue.Key);

			List<Job> jobs = Context.Jobs.Where(x => x.Name == jobValid.ValidationValue.Key).ToList();

			if(jobs.Count > 1)
			{
				MessageBox.Show(string.Format("Невозможно сохрать изменения так как есть несколько должностей с одинаковым названием '{0}'",
											  jobValid.ValidationValue));
				return;
			}

            EditableItem.Job = jobs[0];
            
            base.Commit();
        }

        public override void Dispose()
        {
            orgValid.PropertyChanged -= OrgValidPropertyChanged;
            empValid.PropertyChanged -= EmpValidPropertyChanged;
        }

        #endregion
    }
}
